package cn.edu.stu.syllabus.utils;

import android.content.Context;
import android.content.SharedPreferences;
import android.support.annotation.ColorInt;
import android.support.v4.content.ContextCompat;

import com.google.gson.reflect.TypeToken;

import java.util.HashMap;
import java.util.Map;

import cn.edu.stu.syllabus.application.SyllabusApplication;
import cn.edu.stu.syllabus.datas.ColorHolder;

/**
 * Created by daidaijie on 2017/3/23.
 * 用于根据 单个对象->颜色 获取管理的类，以type作为键获取对应的颜色
 */

public class ColorMapper {

    private static final String TAG = "ColorMapper";

    private final String EXTRA_TYPE_COLOR_MAP = "typeColorMap";

    private final String EXTRA_COLOR_INDEX = "colorIndex";

    private SharedPreferences mSharedPreferences;

    private SharedPreferences.Editor mEditor;

    private Map<String, Integer> mTypeColorMap;

    private int mColorIndex;

    /**
     * 根据name获取对应的ColorMapper类
     * @param name 某个对象对应的标记
     */
    public ColorMapper(String name) {

        String fileName = TAG + "_" + name;

        mSharedPreferences = SyllabusApplication.getContext()
                .getSharedPreferences(fileName, Context.MODE_PRIVATE);
        mEditor = mSharedPreferences.edit();

        String typeColorMapString = mSharedPreferences.getString(EXTRA_TYPE_COLOR_MAP, "");
        if (typeColorMapString.isEmpty()) {
            mTypeColorMap = new HashMap<>();
        } else {
            mTypeColorMap = GsonUtils.getInstance().fromJson(typeColorMapString
                    , new TypeToken<Map<String, Integer>>() {
                    }.getType());
        }
        mColorIndex = mSharedPreferences.getInt(EXTRA_COLOR_INDEX, 0);
    }

    /**
     * 根据type获取对应的颜色
     * @param type 对象的type
     * @return type对应的颜色
     */
    @ColorInt
    public int getTypeColor(String type) {
        if (!mTypeColorMap.containsKey(type)) {
            int color = ContextCompat.getColor(
                    SyllabusApplication.getContext(), ColorHolder.bgColors[mColorIndex++]
            );
            mTypeColorMap.put(type, color);
            String typeColorMapString = GsonUtils.getInstance().toJson(mTypeColorMap);
            mEditor.putString(EXTRA_TYPE_COLOR_MAP, typeColorMapString);
            mEditor.putInt(EXTRA_COLOR_INDEX, mColorIndex);
            mEditor.apply();
        }
        return mTypeColorMap.get(type);

    }

}
